//
//  network_data.cpp
//  testpcap
//
//  Created by bugforever on 1/14/15.
//  Copyright (c) 2015 bugforever. All rights reserved.
//

#include "network_data.h"


network_data::network_data()
:m_ref(0)
,m_ptr_data(0)
,m_data_size(0)
{
    ;
}

network_data::~network_data()
{
    delete []m_ptr_data;
}

int network_data::add_ref()
{
    return ++m_ref;
}

int network_data::release()
{
    m_ref--;
    
    if( m_ref == 0 )
    {
        delete this;
        return 0;
    }
    
    return m_ref;
}

unsigned char * network_data::get_raw_data()
{
    return m_ptr_data;
}

int network_data::get_raw_data_size()
{
    return m_data_size;
}

void network_data::set_tag( NETWORK_DATA_TAG tag , int data_offset )
{
    m_offset_map[ tag ] = data_offset;
}

unsigned char * network_data::get_data_by_tag( NETWORK_DATA_TAG tag )
{
    if( m_offset_map.find( tag ) != m_offset_map.end() )
        return m_ptr_data + m_offset_map[ tag ];
    
    return 0;
}

int network_data::get_datasize_by_tag( NETWORK_DATA_TAG tag )
{
    if( m_offset_map.find( tag ) != m_offset_map.end() )
        return m_data_size - m_offset_map[ tag ];
    
    return -1;
}

int network_data::get_offset_by_tag( NETWORK_DATA_TAG tag )
{
    if( m_offset_map.find( tag ) != m_offset_map.end() )
        return m_offset_map[ tag ];
    
    return -1;
}


int network_data::append_data( unsigned char * ptr_data, int size )
{
    unsigned char * ptr_temp = new unsigned char[ size + m_data_size ];
    
    if( m_ptr_data )
        memcpy( ptr_temp , m_ptr_data , m_data_size );
    
    if( ptr_data )
        memcpy(ptr_temp + m_data_size , ptr_data, size );
    
    delete []m_ptr_data;
    
    m_ptr_data = ptr_temp;
    m_data_size = m_data_size + size;
    
    return m_data_size;
}

interface_network_data * network_data::duplicate()
{
    network_data * ptr_duplicate = new network_data();
    
    ptr_duplicate->m_offset_map = m_offset_map;
    ptr_duplicate->m_ptr_data = new unsigned char[ m_data_size ];
    memcpy(ptr_duplicate->m_ptr_data, m_ptr_data, m_data_size);
    ptr_duplicate->m_data_size = m_data_size;
    
    ptr_duplicate->add_ref();
    
    return ptr_duplicate;
}





